package com.sg.common.empty.web;

import java.math.BigInteger;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dingtalk.openapi.demo.auth.AuthHelper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import com.sg.activiti.service.MyActivitiService;
import com.sg.common.empty.core.ConditionRes;
import com.sg.common.empty.core.Conditions;
import com.sg.common.empty.core.Params;
import com.sg.common.empty.service.CfgService;
import com.sg.common.http.HttpHelper;
import com.sg.common.utils.Constant;
import com.sg.common.utils.DateTimeUtils;
import com.sg.common.utils.Generate;
import com.sg.common.utils.UUIDGenerator;

@Repository
@Controller
@RequestMapping(value = "/mob")
public class MobController {

	private Logger logger = Logger.getLogger(getClass());
	// final String SEPORATOR = System.getProperty("line.separator");
	@Autowired
	MyActivitiService myActivitiService;

	@Autowired
	CfgService service;

	@RequestMapping(value = "/{tb1}/{tb2}/select")
	@ResponseBody
	public Object select(HttpServletRequest request) throws Exception {
		String route = (String) request.getAttribute("conf.route");
		ConditionRes cr = Conditions.init(request).buildCon();
		String oransql = Constant.get(route + ".sql");
		oransql = oransql.replace("@conditions", cr.getSql());
		String res = Constant.get(route + ".res");
		List<Map<String, Object>> dataList = service.queryBySqlToMap(oransql,
				cr.getParams(), res.split(","));

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("items", dataList);
		map.put("code", 1);
		return map;
	}

	@RequestMapping(value = "/alipay/dd/getConfig")
	@ResponseBody
	public Object getConfig(HttpServletRequest request) throws Exception {
		// TODO 如果有js，使用js确定使用哪个sql
		// logger.info("key:ghsdgdfg");
		JSONObject res = new JSONObject();
		String url = request.getParameter("ddurl");
		Map<String, String> config = AuthHelper.getConfig(url, null);
		return config;
	}

	@RequestMapping(value = "/{tb1}/{tb2}/list")
	@ResponseBody
	public Object find(HttpServletRequest request) throws Exception {
		String route = (String) request.getAttribute("conf.route");
		// TODO 如果有js，使用js确定使用哪个sql
		Conditions condis = Conditions.init(request);
		ConditionRes cr = condis.buildCon();
		String sorts = condis.buildSorts();
		String limit = condis.buildLimit();

		// 替换
		String orancsql = Constant.get(route + ".csql");
		String oransql = Constant.get(route + ".sql");
		orancsql = orancsql.replace("@conditions", cr.getSql()).replace(
				"@orderby", sorts);
		oransql = oransql.replace("@conditions", cr.getSql())
				.replace("@orderby", sorts).replace("@limit", limit);

		List<Object> countList = service.queryBySql(orancsql, cr.getParams());
		String res = Constant.get(route + ".res");
		List<Map<String, Object>> dataList = service.queryBySqlToMap(oransql,
				cr.getParams(), res.split(","));

		int count = ((BigInteger) countList.get(0)).intValue();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("items", dataList);
		map.put("total", count);
		map.put("code", 2000);
		return map;
	}

	@RequestMapping(value = "/fs/restaurants/list")
	@ResponseBody
	public Object list(HttpServletRequest request) throws Exception {
		String route = (String) request.getAttribute("conf.route");
		// TODO 如果有js，使用js确定使用哪个sql
		Conditions condis = Conditions.init(request);
		ConditionRes cr = condis.buildCon();
		String sorts = condis.buildSorts();
		String limit = condis.buildLimit();

		// 替换
		String oransql = Constant.get(route + ".sql");
		oransql = oransql.replace("@conditions", cr.getSql())
				.replace("@orderby", sorts).replace("@limit", limit);

		String res = Constant.get(route + ".res");
		List<Map<String, Object>> dataList = service.queryBySqlToMap(oransql,
		// cr.getParams(),
				res.split(","));

		// Map<String, Object> map = new HashMap<String, Object>();
		// map.put("items", dataList);
		return dataList;
	}

	@RequestMapping(value = {"/fs/restaurants/shopDetail","/{tb1}/{tb2}/detail"}, method = RequestMethod.GET)
	@ResponseBody
	public Object shopDetail(HttpServletRequest request) throws Exception {
		Object listDate = null;
		String header = (String) request.getAttribute("conf.header");
		String route = (String) request.getAttribute("conf.route");
		// TODO 如果有js，使用js确定使用哪个sql
		Conditions condis = Conditions.init(request);
		ConditionRes cr = condis.buildCon();
		String sorts = condis.buildSorts();
		String limit = condis.buildLimit();
		String id = (String) request.getParameter("id");
		String oransql =
		Constant.get(route + ".sql");
		oransql = oransql.replace("@conditions", cr.getSql())
				.replace("@orderby", sorts).replace("@limit", limit);
		String res =
		// "id,name,address,tel";
		Constant.get(route + ".res");

		List<Map<String, Object>> detail = service.queryBySqlToMap(oransql,
				cr.getParams(), res.split(","));
		return detail.get(0);
	}

	@RequestMapping(value = "/fs/restaurants/menu", method = RequestMethod.GET)
	@ResponseBody
	public Object menu(HttpServletRequest request) throws Exception {
		JSONObject res = new JSONObject();
		String route = (String) request.getAttribute("conf.route");
		// TODO 如果有js，使用js确定使用哪个sql
		Conditions condis = Conditions.init(request);
		ConditionRes cr = condis.buildCon();
		String restaurantId = request.getParameter("restaurantId");
		String type = request.getParameter("type");
		String sorts = condis.buildSorts();
		// String limit = condis.buildLimit();
		// String header = (String) request.getAttribute("conf.header");
		// TODO 如果有js，使用js确定使用哪个sql
		String oransql_kind = Constant.get(route + ".sql_kind");
		oransql_kind = oransql_kind.replace("@conditions", cr.getSql())
				.replace("@orderby", sorts);
		String res_kind = Constant.get(route + ".res_kind");

		List<Map<String, Object>> menu = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> kindList = service.queryBySqlToMap(
				oransql_kind, cr.getParams(), res_kind.split(","));

		List<Object> al = new ArrayList<Object>();
		// custom deal with condition
		al.addAll(Arrays.asList(cr.getParams()));
		// 自助订餐设定供应时间 8:00~9:45定午餐 13:00~15:45定午餐
		// 天鹅荡食堂、松陵食堂、元和食堂、控制中心食堂、太平食堂、桑田岛食堂
		if (StringUtils.equals(restaurantId, "1")
				|| StringUtils.equals(restaurantId,
						"8a8aa7816144b48e016145b339630008")
				|| StringUtils.equals(restaurantId,
						"8a8aa7816144b48e016145b4749e0009")
				|| StringUtils.equals(restaurantId,
						"8a8aa7816145ff9401618387c679006b")
				|| StringUtils.equals(restaurantId,
						"8a8aa7816145ff9401618389befb006c")
				|| StringUtils.equals(restaurantId,
						"8a8aa7816145ff940161838a58f8006d")) {
			String currentSection = getCurrentSection(restaurantId);
			if (StringUtils.equals(currentSection, "2")) {
				cr.setSql(cr.getSql() + " and ifLunch='1'");
			} else if (StringUtils.equals(currentSection, "3")) {
				cr.setSql(cr.getSql() + " and ifDinner='1'");
			} else if (StringUtils.equals(currentSection, "test")) {
			} else {
				JSONObject res2 = new JSONObject();
				res2.put("code", "4000");
				res2.put("msg",
						"自助订餐模式设定供应时间为 7:00~9:15定午餐、 12:00~14:30定午晚餐！请按照规定时间进行订餐！");
				return res2;
			}
		} else if (StringUtils.equals(restaurantId,
				"8a8aa79d60bfaee70160bfb84af10001")) {
			// } else if (StringUtils.equals(restaurantId, "2")) {
			String currentSection = getCurrentSection(restaurantId);
			if (!StringUtils.equals(currentSection, "2")
					&& !StringUtils.equals(currentSection, "test")) {
				JSONObject res2 = new JSONObject();
				res2.put("code", "4000");
				res2.put("msg", "天平食堂设定供应时间为12:30~15:45定下一个工作日的午餐！请按照规定时间进行订餐！");
				return res2;
			}
			res.put("workDay", getWorkDay());
		}
		cr.setParams(al.toArray());
		String oransql_food = Constant.get(route + ".sql_food");
		oransql_food = oransql_food.replace("@conditions", cr.getSql())
				.replace("@orderby", "").replace("@limit", "");
		String res_food = Constant.get(route + ".res_food");

		List<Map<String, Object>> foodList = service.queryBySqlToMap(
				oransql_food, cr.getParams(), res_food.split(","));
		if (foodList.size() == 0) {
			JSONObject res2 = new JSONObject();
			res2.put("code", "5000");
			res2.put("msg", "该餐厅暂时未设置菜单，请点击食堂详情，联系食堂管理员!");
			return res2;
		}
		for (Map kind : kindList) {
			Map<String, Object> map = new HashMap<>();

			String currentKind = (String) kind.get("id");

			List<Map<String, Object>> foodsList = new ArrayList<Map<String, Object>>();
			for (Map food : foodList) {
				Object foodKind = food.get("kind");
				if (foodKind != null) {
					String fkStr = (String) foodKind;
					if (fkStr.contains(currentKind)) {
						foodsList.add(food);
					}
				}
			}
			if (foodsList.size() > 0) {
				map.putAll(kind);
				map.put("foods", foodsList);
				menu.add(map);
			}
		}
		res.put("code", "2000");
		res.put("menu", menu);
		return res;
	}

	/**
	 * 外卖型食堂8:00~9:45定午餐 13:00~15:45定午餐 自取型食堂13:00~15:45定下一个工作日的午餐
	 * 
	 * @param type
	 *            1 外卖型食堂 2自取型食堂
	 * @return
	 */
	private String getCurrentSection(String restaurantId) {
		// TODO Auto-generated method stub
		String nowTime = DateTimeUtils.formatDate(
				new Timestamp(System.currentTimeMillis()), "HHmm"); // yyyyMMdd
		System.out.println("getCurrentSection_nowTime:" + nowTime);
		System.out.println("restaurantId:" + restaurantId);
		String isTest = Constant.get("isTest");
		if (StringUtils.isNotEmpty(isTest)) {
			return "test";
		}
		// 自助订餐 7:00~9:15定午餐、 12:00~14:30定午晚餐
		// 天鹅荡食堂、松陵食堂、元和食堂、控制中心食堂、太平食堂、桑田岛食堂
		if (StringUtils.equals(restaurantId, "1")
				|| StringUtils.equals(restaurantId,
						"8a8aa7816144b48e016145b339630008")
				|| StringUtils.equals(restaurantId,
						"8a8aa7816144b48e016145b4749e0009")
				|| StringUtils.equals(restaurantId,
						"8a8aa7816145ff9401618387c679006b")
				|| StringUtils.equals(restaurantId,
						"8a8aa7816145ff9401618389befb006c")
				|| StringUtils.equals(restaurantId,
						"8a8aa7816145ff940161838a58f8006d")) {
			if (700 < Integer.parseInt(nowTime)
					&& Integer.parseInt(nowTime) < 915) {
				return "2";
			} else if (1200 < Integer.parseInt(nowTime)
					&& Integer.parseInt(nowTime) < 1430) {
				return "3";
			}
		}
		// 天平食堂自助订餐12:30~15:45定下一个工作日的午餐
		else if (StringUtils.equals(restaurantId,
				"8a8aa79d60bfaee70160bfb84af10001")) {
			if (Constant.getInt(restaurantId + "_startTime") < Integer
					.parseInt(nowTime)
					&& Integer.parseInt(nowTime) < Constant.getInt(restaurantId
							+ "_endTime")) {
				return "2";
			}
		}
		return "-1";
	}

	@RequestMapping(value = "/login/user/getUser", method = RequestMethod.GET)
	@ResponseBody
	public Object getUser(HttpServletRequest request) throws Exception {
		Object user_name = request.getSession().getAttribute("user_name");
		Object user_code = (String) request.getSession().getAttribute(
				Constant.SESSION_MEMBER_CODE);
		Object user_tel = request.getSession().getAttribute("user_tel");
		//获取人员所属部门
		String sql_user = "SELECT cfg_member.code,IFNULL(cfg_org.descr,''),IFNULL(cfg_post.descr,''),cfg_member.dept FROM cfg_member left join cfg_org on dept=cfg_org.id LEFT JOIN cfg_post on post= cfg_post.id where cfg_member.code=?";
		String res_user = "code,dept,position,deptId";
		List<Map<String, Object>> userList = service.queryBySqlToMap(
				sql_user, new Object[] { user_code },
				res_user.split(","));
		
		JSONObject jObject = new JSONObject();
		String dept="";
		String position="";			// 2019.6.19增加个人岗位信息
		String deptId="";			//2019.8.20 增加部门ID
		if(userList.size()>0)
			dept=(String) userList.get(0).get("dept");
		position=(String) userList.get(0).get("position");
		deptId=(String) userList.get(0).get("deptId");
		jObject.put("user_dept", dept);
		jObject.put("user_position", position);
		jObject.put("user_deptId", deptId);
		jObject.put("user_name", user_name);
		jObject.put("user_code", user_code);
		jObject.put("user_tel", user_tel);
		return jObject;
		
	}

	@RequestMapping(value = "/shopping/carts/checkout", method = RequestMethod.POST)
	@ResponseBody
	public Object checkout(HttpServletRequest request,
			@RequestBody Object requestBody) throws Exception {
		// Map<String, Object> rb = (Map<String, Object>) requestBody;
		Object rb2 = requestBody;
		Map<String, Object> rb = (Map<String, Object>) rb2;
		ArrayList<Object> entities = (ArrayList<Object>) rb.get("entities");
		String shopId = (String) rb.get("shopId");
		JSONObject res = new JSONObject();

		JSONObject cart = new JSONObject();
		cart.put("id", 868719);
		cart.put("groups", entities);

		ArrayList<Map<String, Object>> foods = (ArrayList<Map<String, Object>>) entities
				.get(0);
		float total = 0;
		float prices = 0;
		for (Map<String, Object> food : foods) {
			prices = Integer.parseInt(food.get("quantity").toString())
					* Float.parseFloat(food.get("price").toString());
			total = total + prices;
		}
		cart.put("total", total);

		String sql_restaurant = "select id,descr,type from fs_restaurant where id = ?";
		String res_restaurant = "id,descr,type";
		List<Map<String, Object>> restaurantList = service.queryBySqlToMap(
				sql_restaurant, new Object[] { shopId },
				res_restaurant.split(","));

		JSONObject restaurant_info = new JSONObject();
		restaurant_info.put("name", restaurantList.get(0).get("descr"));
		restaurant_info.put("type", restaurantList.get(0).get("type"));
		cart.put("restaurant_info", restaurant_info);
		res.put("cart", cart);
		return res;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/users/carts/placeOrders", method = RequestMethod.POST)
	@ResponseBody
	public Object placeOrders(HttpServletRequest request,
			@RequestBody Map<String, Object> requestBody) throws Exception {
		Map<String, Object> rb = (Map<String, Object>) requestBody;
		
		String user_name = (String) rb.get("user_name");
		String user_tel = (String) rb.get("user_tel");
		String user_code = (String) rb.get("user_code");
		String address = (String) rb.get("address");
		String stationId = (String) rb.get("stationId");
		String description = (String) rb.get("description");
		String restaurantId = (String) rb.get("restaurantId");
		String restaurantType = (String) rb.get("restaurantType");
		ArrayList<Object> entities = (ArrayList<Object>) rb.get("entities");

		String currentSection = getCurrentSection(restaurantId);
		if (StringUtils.equals(currentSection, "-1")) {
			JSONObject res = new JSONObject();
			res.put("code", "5000");
			res.put("msg", "您好，当前已经超过订餐时间点，请按照规定时间进行订餐！");
			return res;
		}
		ArrayList<Map<String, Object>> foods = (ArrayList<Map<String, Object>>) entities
				.get(0);
		float total = 0;
		float prices = 0;
		String check_res = checkRemainNum(restaurantId, foods);
		if (StringUtils.isNotEmpty(check_res)) {
			JSONObject res = new JSONObject();
			res.put("code", "5000");
			res.put("msg", check_res);
			return res;
		}

		String sql_restaurant = "select id,IFNULL(linid,''),IFNULL(lindc,'') from fs_restaurant where id = ?";
		String res_restaurant = "id,linid,lindc";
		List<Map<String, Object>> restaurantList = service.queryBySqlToMap(
				sql_restaurant, new Object[] { restaurantId },
				res_restaurant.split(","));
		String linid = restaurantList.get(0).get("linid").toString();
		String lindc = restaurantList.get(0).get("lindc").toString();

		for (Map<String, Object> food : foods) {
			prices = Integer.parseInt(food.get("quantity").toString())
					* Float.parseFloat(food.get("price").toString());
			total = total + prices;
		}
		// enable '有效性 0-待接收 10-已接收 20-配送中 30-已配送 40-已完成'
		String sql_order = "insert into fs_order (id,restaurantId,no,epnum,name,location,stationId,tel,total,section,createDate,remark,daily,payStatus,enable,linid,lindc) values(?,?,?,?,?,?,?,?,?,?,?,?,?,'0','0',?,?)";
		List<String> params_order = new ArrayList<String>();
		params_order.add(0, new UUIDGenerator().generate().toString());
		params_order.add(1, restaurantId);
		params_order.add(
				2,
				"STWM"
						+ DateTimeUtils.formatDate(
								new Timestamp(System.currentTimeMillis()),
								"yyyyMMddhhss") + Generate.generateWord(2));
		params_order.add(3, user_code);
		params_order.add(4, user_name);
		params_order.add(5, address);
		params_order.add(6, stationId);
		params_order.add(7, user_tel);
		params_order.add(8, String.valueOf(total));
		params_order.add(9, currentSection);
		params_order.add(10, DateTimeUtils.formatDate(
				new Timestamp(System.currentTimeMillis()), "yyyy-MM-dd HH:mm"));
		params_order.add(11, description);
		String daily = "";

		// 食堂类型 type 1:外卖类型 取餐日期为当天 2：自取类型 取餐日期为后一天的工作日
		if (StringUtils.equals(restaurantType, "2")) {
			daily = getWorkDay();
		} else {
			daily = DateTimeUtils.formatDate(
					new Timestamp(System.currentTimeMillis()), "yyyy-MM-dd");
		}
		params_order.add(12, daily);
		params_order.add(13, linid);
		params_order.add(14, lindc);

		service.excuteBySql(sql_order, params_order.toArray());

		String sql_orderDetail = "insert into fs_orderdetail (id,orderId,foodId,descr,longDescr,quantity,price,createDate) values(?,?,?,?,?,?,?,?)";

		for (Map<String, Object> food : foods) {
			List<String> params_orderDetail = new ArrayList<String>();
			params_orderDetail
					.add(0, new UUIDGenerator().generate().toString());
			params_orderDetail.add(1, params_order.get(0));
			params_orderDetail.add(2, (String) food.get("id"));
			params_orderDetail.add(3, (String) food.get("name"));
			params_orderDetail.add(4, (String) food.get("name"));
			params_orderDetail.add(5, String.valueOf(food.get("quantity")));
			params_orderDetail.add(6, String.valueOf(food.get("price")));
			params_orderDetail.add(7, DateTimeUtils.formatDate(new Timestamp(
					System.currentTimeMillis()), "yyyy-MM-dd HH:mm"));
			service.excuteBySql(sql_orderDetail, params_orderDetail.toArray());
		}

		Object listDate = null;
		String route = (String) request.getAttribute("conf.route");
		String header = (String) request.getAttribute("conf.header");

		Map<String, String> ac = request.getParameterMap();
		Enumeration ac2 = request.getAttributeNames();
		// TODO 如果有js，使用js确定使用哪个sql
		JSONObject res = new JSONObject();
		res.put("order_id", params_order.get(0));
		res.put("code", "2000");
		return res;
	}

	private String getWorkDay() {
		String daily = DateTimeUtils.formatDate(
				new Timestamp(System.currentTimeMillis() + Constant.DAY_SPAN),
				"yyyy-MM-dd");
		// daily = "2018-02-15";
		String type = "1";
		while (!StringUtils.equals(type, "0")) {

			if (Constant.HOLIDAY.get(daily) != null) {
				type = Constant.HOLIDAY.get(daily);
			} else {
				String sql_holiday = "select date,type from fs_holiday where date = ?";
				String res_holiday = "date,type";
				List<Map<String, Object>> holidayList = service
						.queryBySqlToMap(sql_holiday, new Object[] { daily },
								res_holiday.split(","));
				if (holidayList.size() > 0) {
					type = holidayList.get(0).get("type").toString();
					Constant.HOLIDAY.put(holidayList.get(0).get("date")
							.toString(), type);
				}
			}
			if (!StringUtils.equals(type, "0"))
				daily = DateTimeUtils.formatDate(new Timestamp(DateTimeUtils
						.strToDate(daily, "yyyy-MM-dd").getTime()
						+ Constant.DAY_SPAN), "yyyy-MM-dd");
		}
		return daily;
	}

	@RequestMapping(value = "/alipay/rsa/getInfo")
	@ResponseBody
	public Object getInfo(HttpServletRequest request) throws Exception {
		String currentTime = DateTimeUtils.formatDate(
				new Timestamp(System.currentTimeMillis()),
				"yyyy-MM-dd HH:mm:ss");

		String order_id = request.getParameter("order_id");

		String sql_order = "select no,epnum,name,tel,location,total,restaurantId from fs_order where id = ?";
		String res_order = "no,epnum,name,tel,location,total,restaurantId";

		String sql_orderdetail = "select foodId,descr,quantity,price from fs_orderdetail where orderId = ?";
		String res_orderdetail = "id,name,quantity,price";

		List<Map<String, Object>> orderList = service.queryBySqlToMap(
				sql_order, new Object[] { order_id }, res_order.split(","));

		List<Map<String, Object>> orderdetailList = service.queryBySqlToMap(
				sql_orderdetail, new Object[] { order_id },
				res_orderdetail.split(","));

		if (orderList.size() != 1) {
			JSONObject res = new JSONObject();
			res.put("code", "4000");
			res.put("msg", "订单查找异常，请重新支付！");
			return res;
		}
		// 检查剩余数量是否满足订单需求
		String restaurantId = orderList.get(0).get("restaurantId").toString();
		String check_res = checkRemainNum(restaurantId, orderdetailList);
		if (StringUtils.isNotEmpty(check_res)) {
			JSONObject res = new JSONObject();
			res.put("code", "5000");
			res.put("msg", check_res);
			return res;
		}

		String privateKey = "";
		String subject = "";
		Map<String, String> params = new HashMap<String, String>();
		// 天鹅荡食堂、松陵食堂、元和食堂、控制中心食堂、太平食堂、桑田岛食堂
		if (StringUtils.equals(restaurantId, "1")
				|| StringUtils.equals(restaurantId,
						"8a8aa7816144b48e016145b339630008")
				|| StringUtils.equals(restaurantId,
						"8a8aa7816144b48e016145b4749e0009")
				|| StringUtils.equals(restaurantId,
						"8a8aa7816145ff9401618387c679006b")
				|| StringUtils.equals(restaurantId,
						"8a8aa7816145ff9401618389befb006c")
				|| StringUtils.equals(restaurantId,
						"8a8aa7816145ff940161838a58f8006d")) {
			params.put("app_id", "2017103109629984");
			privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKM4ecDUfLZ2TYsRHkLA9udZQzZpcIztV20Zw9bMW1yUJuVnr5AZmiec2l4lWVdYqeTAgk29DhT0q+ACVNsoSyWGE2TVlywVoikSEEQo5MYNCtpJU5crYkMQpPwNCpetFd+m9w1MJOqd+SEuUlg7HcRQ6/UODZhL8fUoaJvzrMMpAgMBAAECgYB6EJ5da4vpGQhc3Gx5F76Ovd7aLniRrF4ZpY8kcKhS0ClWnvhZGAyFW3Sju+LYw+IqxR2t7Zk+asyvNo8nZzbqo1+0hhPIzrX70cRM4R1k2HHidrjV0bCt4zC/dtRSLEj14Ws8HMsMlLXhMCYz5Vf3tyOWq1gf4TutSSvUCDuUEQJBAMylDm9ibDJGnpD78fsykphGvVJz0T4eGTwlEkVsGd6yH0rZ5ex5/qRvUuVEJo/I8dY9FMN2VmKyZajqJDET5a8CQQDMLjfIK8V+yScOOxWU9SGlU+HrArlbZni+NtDwvMKKXflCbkXQfk7yBmFBhCz4gp0for+0QJO9xcitY8gHtnKnAkB74Q6z7miApq8mJN1+qkaDV48Tcnifmai899PvolimrjyzGuRMGi1DbQBJOM//Ci0a+y6ug9wXMtbHQbVW4CyRAkB+dhXIngu5hj7xWnj4hIctTfH8S/if+qzIK01n/ZGEf8XVdlU5WDHvRzJPkN0FomhM4tFXhDO9c1Xixo1q8X67AkB+TRF5yBOuwwMElr+irjlaEpgDoGicrq06TlE1wTSfltkF+Z4AEDkcZTuByMCEDtmmgK8m7AG22DUGeZuJUL41";
			subject = "天鹅荡食堂自助订餐";
		} else if (StringUtils.equals(restaurantId,
				"8a8aa79d60bfaee70160bfb84af10001")) {
			params.put("app_id", "2017062707580825");
			privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ9D8J81iOixJmPifEjj4Xx1p3x+RAu0pjLmf7bYRzXFdRChJanabzKEcgDoPOkkigN+JAxsuOFTa5q4zaZvLBoijARor+/wmmkADx8nFHboFWcsSm0zdjFWXMFIKZc5Y02A4FRVfKzEabGLWnizYTETTBVBJbKTsZUOfWcnwoLrAgMBAAECgYEAmx1bfGRyjFcE0eGjNIaldUdNsWV0toXiHM778kQgztEam/CnMw+on2X5dsK5mERbGt2/FE7LncFWmuGEgaXjJ52/W+sEK+yRNlJV20ckJGHzQmL+dwLYzWUchvRMP6eZ2Ch5smlO3CyyoASuov7e0OUzX8jEk3Eyj5Va4myglfECQQDwmKugYsbmDkLjUatmz/7pvcCXdTuvyAPhFeZOid1MPcKkbLkTwkFxyRfMXiHktp56dsS+OMmBYWjccMRlyEGZAkEAqXZFG71vwVPIYCjTGAMgx7a/WLZ2mgp2kuVvT+fY36cQwfMJD+bofa/sMnWpGN2EiAb7t19DXJd0usnxRPrDIwJBANEpCFtARAWP9FpGj6mrvMJbcei5xA/G5IhzT2qLs9UqA+KJmkQxJk/TMFs8ol6A3Dk+sz9jgtp1YoHxjuulMlECQFDrwB55/GamGnYIqJy7yah0lLTJFKOEQZDt7JSMktxhy7fB1V75laWHH1QNKX1NMl8+bm7nF6ScUkpr6kFVOV8CQDUQPVrdNNMN8l+TpgPUS0ou6IKVXzNkhRLIzFNH5q/1HVnTExS211K1NieT3/howoNofnvLx/iAnspGwdgwmcc=";
			subject = "天平食堂小炒自助订餐";
		} else {
			JSONObject res = new JSONObject();
			res.put("code", "5000");
			res.put("msg", "该店家尚未配置支付宝相关信息，请联系商家！");
			return res;
		}
		params.put(
				"enable_pay_channels",
				"balance,moneyFund,pcredit,pcreditpayInstallment,creditCardExpress,creditCardCartoon,coupon,credit_group,debitCardExpress");
		params.put("method", "alipay.trade.app.pay");
		params.put("charset", "utf-8");
		params.put("sign_type", "RSA");
		params.put("timestamp", currentTime);
		params.put("version", "1.0");
		params.put("notify_url", Constant.get("updateOrder_URL"));
		String out_trade_no = (String) orderList.get(0).get("no");
		String total = (String) orderList.get(0).get("total");
		String name = (String) orderList.get(0).get("name");
		String epnum = (String) orderList.get(0).get("epnum");
		String tel = (String) orderList.get(0).get("tel");
		String location = (String) orderList.get(0).get("location");

		String body = "人员信息：{姓名：" + name + "、工号:" + epnum + "、手机:" + tel
				+ "、地址:" + location + "};订餐清单：{";
		int i = 1;
		for (Map<String, Object> od : orderdetailList) {
			body = body + i + "、菜品名称：" + (String) od.get("name") + "、数量："
					+ (String) od.get("quantity") + "、单价："
					+ (String) od.get("price") + "元;";
			i = i + 1;
		}
		body = body + "总价：" + total + "元。}";
		String biz_content = "{\"timeout_express\":\"15m\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"total_amount\":\""
				+ total
				+ "\",\"subject\":\""
				+ subject
				+ "\",\"body\":\""
				+ body + "\",\"out_trade_no\":\"" + out_trade_no + "\"}";

		params.put("biz_content", biz_content);

		String signRes = AlipaySignature.rsaSign(params, privateKey, "utf-8");
		params.put("sign", signRes);

		Map<String, String> infoMap = new HashMap<String, String>();

		for (Map.Entry<String, String> entry : params.entrySet()) {
			infoMap.put(entry.getKey(),
					URLEncoder.encode(entry.getValue(), "utf-8"));
		}

		String info = AlipaySignature.getSignContent(infoMap);

		JSONObject jObject = new JSONObject();
		jObject.put("info", info);
		jObject.put("code", "2000");
		return jObject;
	}

	private String checkRemainNum(String restaurantId,
			List<Map<String, Object>> foods) {
		String res = "";
		String res_foods = "id,isLimit,limitNum,remainNum,price";
		String sql_foods = "SELECT id,isLimit,limitNum,remainNum,price FROM fs_food WHERE ENABLE = '1' and restaurantId= ?";
		List<Map<String, Object>> foodsList = service.queryBySqlToMap(
				sql_foods, new Object[] { restaurantId }, res_foods.split(","));

		for (Map<String, Object> food : foods) {
			boolean isEnable = false; // 判断前台传来的ID是否存在且有效
			boolean isPrice = false; // 判断前台传来的价格是否和后台一致
			for (Map<String, Object> food_res : foodsList) {
				if (!StringUtils.equals((String) food.get("id"),
						(String) food_res.get("id")))
					continue;
				isEnable = true;
				// 判断价格是否一致
				if (Math.abs(Float.parseFloat(food.get("price").toString())
						- Float.parseFloat(food_res.get("price").toString())) <= 0) {
					isPrice = true;
				}
				if (StringUtils.equals("0", (String) food_res.get("isLimit")))
					break;
				if (Integer.parseInt(food_res.get("remainNum").toString()) <= 0
						|| Integer.parseInt(food_res.get("remainNum")
								.toString())
								- Integer.parseInt(food.get("quantity")
										.toString()) < 0) {
					res = res + food.get("name") + "库存不足,剩余"
							+ food_res.get("remainNum") + "份;";
				}
			}
			if (!isEnable) {
				res = res + food.get("name") + "不存在，清除缓存后，";
			}
			if (!isPrice) {
				res = res + food.get("name") + "价格和后台不一致，清除缓存后，";
			}
		}
		if (StringUtils.isNotEmpty(res))
			res = res + "请重新下单！";
		return res;
	}

	@RequestMapping(value = "/payapi/payment/updateOrder")
	@ResponseBody
	public synchronized Object updateOrder(HttpServletRequest request)
			throws Exception {
		// TODO 如果有js，使用js确定使用哪个sql
		Map<String, String> rsaMap = new HashMap<String, String>();
		@SuppressWarnings("unchecked")
		Map<String, String[]> paramsMap = request.getParameterMap();
		Set<String> keySet = paramsMap.keySet();
		for (String key : keySet) {
			System.out
					.println("key:" + key + ";value:" + paramsMap.get(key)[0]);
			logger.info("key:" + key + ";value:" + paramsMap.get(key));
			rsaMap.put(key, paramsMap.get(key)[0]);
		}
		String out_trade_no = rsaMap.get("out_trade_no");
		String res_order = "id,no,epnum,name,tel,total,paystatus,restaurantId,daily";
		String sql_order = "select id,no,epnum,name,tel,total,paystatus,restaurantId,daily from fs_order where no = ?";
		List<Map<String, Object>> orderList = service.queryBySqlToMap(
				sql_order, new Object[] { out_trade_no }, res_order.split(","));
		if (orderList != null && orderList.size() == 1) {
			String restaurantId = orderList.get(0).get("restaurantId")
					.toString();
			String orderId = orderList.get(0).get("id").toString();
			String epnum = orderList.get(0).get("epnum").toString();
			String tel = StringUtils.right(orderList.get(0).get("tel")
					.toString(), 4);
			String daily = orderList.get(0).get("daily").toString();
			String ALIPAY_PUBLIC_KEY = "";
			String local_app_id = "";
			String local_aseller_id = "";
			String maxNo = "";
			// 天鹅荡食堂、松陵食堂、元和食堂、控制中心食堂、太平食堂、桑田岛食堂
			if (StringUtils.equals(restaurantId, "1")
					|| StringUtils.equals(restaurantId,
							"8a8aa7816144b48e016145b339630008")
					|| StringUtils.equals(restaurantId,
							"8a8aa7816144b48e016145b4749e0009")
					|| StringUtils.equals(restaurantId,
							"8a8aa7816145ff9401618387c679006b")
					|| StringUtils.equals(restaurantId,
							"8a8aa7816145ff9401618389befb006c")
					|| StringUtils.equals(restaurantId,
							"8a8aa7816145ff940161838a58f8006d")) {
				ALIPAY_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB";
				local_app_id = "2017103109629984";
				local_aseller_id = "2088821559166607";
			} else if (StringUtils.equals(restaurantId,
					"8a8aa79d60bfaee70160bfb84af10001")) {
				ALIPAY_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB";
				local_app_id = "2017062707580825";
				local_aseller_id = "2088721391886001";
				maxNo = getMaxNo(daily, service);

			} else {
				return "failure";
			}
			boolean signVerified = AlipaySignature.rsaCheckV1(rsaMap,
					ALIPAY_PUBLIC_KEY, "utf-8"); // 调用SDK验证签名
			// boolean signVerified = true;
			if (signVerified) {
				String total_amount = rsaMap.get("total_amount");
				String seller_id = rsaMap.get("seller_id");
				String app_id = rsaMap.get("app_id");
				boolean eq_app_id = StringUtils.equals(app_id, local_app_id);
				boolean eq_seller_id = StringUtils.equals(seller_id,
						local_aseller_id);
				boolean eq_total_amount = Math.abs(Float
						.parseFloat(total_amount)
						- Float.parseFloat(orderList.get(0).get("total")
								.toString())) <= 0;
				String gmt_payment = rsaMap.get("gmt_payment");
				String trade_status = rsaMap.get("trade_status");
				boolean eq_trade_status = StringUtils.equals("TRADE_SUCCESS",
						trade_status)
						|| StringUtils.equals("TRADE_FINISHED", trade_status);
				// boolean eq_app_id = true;
				// boolean eq_seller_id = true;
				// boolean eq_total_amount = true;
				// System.out.println("eq_app_id" + eq_app_id);
				// System.out.println("eq_seller_id" + eq_seller_id);
				// System.out.println("eq_total_amount" + eq_total_amount);
				if (eq_app_id && eq_seller_id && eq_total_amount
						&& eq_trade_status
						&& StringUtils.isNotEmpty(gmt_payment)) {
					String oransql = "update fs_order set payStatus=1,payTime=?,eatingCode=? where no=?";
					List<String> sqlParams = new ArrayList<String>();
					sqlParams.add(0, gmt_payment);
					Random random = new Random();
					sqlParams.add(
							1,
							maxNo + "-" + tel + "-"
									+ String.valueOf(random.nextInt(9))
									+ String.valueOf(random.nextInt(9)));
					sqlParams.add(2, out_trade_no);
					System.out.println(sqlParams);
					service.excuteBySql(oransql, sqlParams.toArray());

					String sql_orderdetail = "select foodId,descr,quantity,price from fs_orderdetail where orderId = ?";
					String res_orderdetail = "id,name,quantity,price";

					List<Map<String, Object>> orderdetailList = service
							.queryBySqlToMap(sql_orderdetail,
									new Object[] { orderId },
									res_orderdetail.split(","));
					reduceRemainNum(restaurantId, orderdetailList);

					return "success";
				}
			}

		}
		return "failure";
	}

	private static synchronized String getMaxNo(String daily, CfgService service) {
		String maxNo;
		String sql_maxNo = "SELECT id,IFNULL(MAX(left(eatingCode,3)),0) as maxNo FROM fs_order WHERE daily=? AND payStatus='1' AND restaurantId='8a8aa79d60bfaee70160bfb84af10001'";
		String res_maxNo = "id,maxNo";
		List<Map<String, Object>> maxNoList = service.queryBySqlToMap(
				sql_maxNo, new Object[] { daily }, res_maxNo.split(","));
		maxNo = String.valueOf(Integer.parseInt(maxNoList.get(0).get("maxNo")
				.toString()) + 1);
		maxNo = (maxNo.length() == 1 ? "00" + maxNo : maxNo.length() == 2 ? "0"
				+ maxNo : maxNo);
		return maxNo;
	}

	private void reduceRemainNum(String restaurantId,
			List<Map<String, Object>> foods) {
		String res_foods = "id,isLimit,limitNum,remainNum";
		String sql_foods = "SELECT id,isLimit,limitNum,remainNum FROM fs_food WHERE ENABLE = '1' and restaurantId= ?";
		List<Map<String, Object>> foodsList = service.queryBySqlToMap(
				sql_foods, new Object[] { restaurantId }, res_foods.split(","));

		for (Map<String, Object> food : foods) {

			for (Map<String, Object> food_res : foodsList) {
				if (!StringUtils.equals((String) food.get("id"),
						(String) food_res.get("id")))
					continue;
				if (StringUtils.equals("0", (String) food_res.get("isLimit")))
					break;
				else {
					String remainNum = String
							.valueOf(Integer.parseInt(food_res.get("remainNum")
									.toString())
									- Integer.parseInt(food.get("quantity")
											.toString()));
					String oransql = "update fs_food set remainNum=? where id=?";
					List<String> sqlParams = new ArrayList<String>();
					sqlParams.add(0, remainNum);
					sqlParams.add(1, (String) food_res.get("id"));
					service.excuteBySql(oransql, sqlParams.toArray());
				}
			}
		}
	}

	@RequestMapping(value = "/users/orders/getOrderList")
	@ResponseBody
	public Object getOrderList(HttpServletRequest request) throws Exception {

		String user_code = request.getParameter("user_code");
		String page = request.getParameter("page");
		String limit = request.getParameter("limit");

		String limitSql = "";
		if (StringUtils.isNotEmpty(page) && StringUtils.isNotEmpty(limit)) {
			Integer pageInt = Integer.valueOf(page);
			Integer limitInt = Integer.valueOf(limit);
			limitSql += " limit " + (pageInt - 1) * limitInt + "," + limitInt;
		}

		String sql_order = "select fs_order.id,no,epnum,name,fs_order.tel,fs_order.location,total,paystatus,fs_order.createDate,fs_order.daily,fs_order.eatingCode,fs_order.remark,restaurantId,fs_restaurant.descr,CASE fs_order.`enable` WHEN 0 THEN '待接收' WHEN 10 THEN '已接收' WHEN 20 THEN '已配送' WHEN 40 THEN '已完成' END from fs_order inner join fs_restaurant on fs_order.restaurantId=fs_restaurant.id where epnum = ? order by fs_order.createDate desc";
		String res_order = "id,no,epnum,name,tel,location,total_amount,paystatus,createDate,daily,eatingCode,remark,restaurant_id,restaurant_name,enable";

		String sql_orderdetail = "select descr,quantity,price from fs_orderdetail where orderId = ?";
		String res_orderdetail = "name,quantity,price";

		List<Map<String, Object>> orderList = service.queryBySqlToMap(sql_order
				+ limitSql, new Object[] { user_code }, res_order.split(","));

		JSONArray jsonArray = new JSONArray();
		for (Map<String, Object> order : orderList) {
			JSONObject item = new JSONObject();
			item.putAll(order);
			item.put("restaurant_image_url", "");

			JSONObject basket = new JSONObject();

			List<Map<String, Object>> detailList = service.queryBySqlToMap(
					sql_orderdetail, new Object[] { order.get("id") },
					res_orderdetail.split(","));
			basket.put("group", detailList);
			item.put("basket", basket);

			String createDate = order.get("createDate").toString();
			long now = System.currentTimeMillis() / 1000;
			long fromDate = DateTimeUtils.strToDate(createDate,
					"yyyy-MM-dd hh:mm").getTime() / 1000;
			long created_at = now - fromDate;

			JSONObject status_bar = new JSONObject();
			String paystatus = order.get("paystatus").toString();
			if (StringUtils.equals(paystatus, "0") && created_at < 900) {
				status_bar.put("title", "等待支付");
				String formatted_created_at = "";
				if (created_at < 60) {
					formatted_created_at = String.valueOf(created_at) + "秒前";
				} else {
					formatted_created_at = String.valueOf(created_at / 60)
							+ "分钟前";
				}
				item.put("formatted_created_at", formatted_created_at);
			} else if (StringUtils.equals(paystatus, "0") && created_at >= 900) {
				status_bar.put("title", "已超时");
				item.put("formatted_created_at", createDate);
			} else if (StringUtils.equals(paystatus, "1")) {
				status_bar.put("title", "已支付");
				item.put("formatted_created_at", createDate);
			} else {
				status_bar.put("title", "已取消");
				item.put("formatted_created_at", createDate);
			}
			item.put("status_bar", status_bar);
			jsonArray.add(item);
		}

		return jsonArray;
	}

	@RequestMapping(value = "/payapi/payment/queryOrder", method = RequestMethod.GET)
	@ResponseBody
	public Object queryOrder(HttpServletRequest request) throws Exception {

		String order_id = request.getParameter("order_id");
		String user_code = request.getParameter("user_code");

		String route = (String) request.getAttribute("conf.route");
		// TODO 如果有js，使用js确定使用哪个sql
		Conditions condis = Conditions.init(request);
		ConditionRes cr = condis.buildCon();
		String sorts = condis.buildSorts();
		String limit = condis.buildLimit();

		// 替换
		String oransql = Constant.get(route + ".sql");
		oransql = oransql.replace("@conditions", cr.getSql())
				.replace("@orderby", sorts).replace("@limit", limit);

		String resa = Constant.get(route + ".res");
		List<Map<String, Object>> totalList = service.queryBySqlToMap(oransql,
				cr.getParams(), resa.split(","));

		// TODO 如果有js，使用js确定使用哪个sql
		JSONObject res = new JSONObject();
		JSONObject resultData = new JSONObject();

		JSONObject orderInfo = new JSONObject();
		orderInfo.put("orderAmount", totalList.get(0).get("total"));

		resultData.put("orderInfo", orderInfo);
		res.put("message", "请在15分钟内支付!（注意：系统暂时不支持退款业务）");
		res.put("resultData", resultData);
		return res;
	}

	@RequestMapping(value = "/{tb1}/{tb2}/cities", method = RequestMethod.GET)
	@ResponseBody
	public Object cities(HttpServletRequest request) throws Exception {
		Object listDate = null;
		String route = (String) request.getAttribute("conf.route");
		String header = (String) request.getAttribute("conf.header");
		// TODO 如果有js，使用js确定使用哪个sql

		JSONObject jObject = new JSONObject();
		jObject.put("id", 1);
		jObject.put("name", "上海");
		jObject.put("abbr", "SH");
		jObject.put("area_code", "021");
		jObject.put("sort", "9999");
		jObject.put("latitude", 31.23037);
		jObject.put("longitude", 121.473701);
		jObject.put("is_map", true);
		jObject.put("pinyin", "shanghai");
		return jObject;
	}

	@RequestMapping(value = "/users/Tools/holiday", method = RequestMethod.GET)
	@ResponseBody
	public Object holiday(HttpServletRequest request) throws Exception {
		String year = request.getParameter("year");
		String date = year + "-01-01";
		Date today = DateTimeUtils.strToDate(date, "yyyy-MM-dd");
		String newYear = year;
		while (StringUtils.equals(year, newYear)) {
			date = DateTimeUtils.formatDate(today, "yyyy-MM-dd");
			String check_date = DateTimeUtils.formatDate(today, "yyyyMMdd");
			Map<String, String> http_res = HttpHelper
					.httpGet_map("http://api.goseek.cn/Tools/holiday?date="
							+ check_date);
			String code = String.valueOf(http_res.get("code"));
			if (StringUtils.equals(code, "10000")) {
				String sql_order = "insert into fs_holiday(id,date,type) values(?,?,?)";
				List<String> params_order = new ArrayList<String>();
				params_order.add(0, new UUIDGenerator().generate().toString());
				params_order.add(1, date);
				String type = String.valueOf(http_res.get("data"));
				params_order.add(2, type);
				service.excuteBySql(sql_order, params_order.toArray());
			}
			today = new Date(today.getTime() + Constant.DAY_SPAN);
			Calendar c = Calendar.getInstance();
			c.setTime(today);
			newYear = String.valueOf(c.get(Calendar.YEAR));

		}
		JSONObject res = new JSONObject();
		res.put("code", "2000");
		return res;
	}

	@RequestMapping(value = "/fs/address/list")
	@ResponseBody
	public Object getAddress(HttpServletRequest request) throws Exception {
		String route = (String) request.getAttribute("conf.route");
		// TODO 如果有js，使用js确定使用哪个sql
		Conditions condis = Conditions.init(request);
		ConditionRes cr = condis.buildCon();
		String sorts = condis.buildSorts();
		String limit = condis.buildLimit();

		// 替换
		String oransql_idlns = Constant.get(route + ".sql_idlns");
		oransql_idlns = oransql_idlns.replace("@conditions", cr.getSql())
				.replace("@orderby", sorts).replace("@limit", limit);

		String res_idlns = Constant.get(route + ".res_idlns");
		List<Map<String, Object>> idlnList = service.queryBySqlToMap(
				oransql_idlns, cr.getParams(), res_idlns.split(","));

		String oransql_idsts = Constant.get(route + ".sql_idsts");
		oransql_idsts = oransql_idsts.replace("@conditions", cr.getSql())
				.replace("@orderby", sorts).replace("@limit", limit);
		String res_idsts = Constant.get(route + ".res_idsts");
		List<Map<String, Object>> idstFullList = service.queryBySqlToMap(
				oransql_idsts, cr.getParams(), res_idsts.split(","));

		Map<String, Object> map = new HashMap<String, Object>();
		List<String> lines = new ArrayList<String>();
		for (Map<String, Object> mp : idlnList) {

			String lindc = (String) mp.get("lindc");
			lines.add(lindc);
			List<Map<String, Object>> idstList = new ArrayList<Map<String, Object>>();
			for (Map<String, Object> idstMap : idstFullList) {
				if (StringUtils.equals(lindc, (String) idstMap.get("lindc"))) {
					idstList.add(idstMap);
				}
			}
			map.put(lindc, idstList);
		}
		map.put("lines", lines);
		return map;
	}

	@RequestMapping(value = "/{tb1}/{tb2}/add")
	@ResponseBody
	public Object add(HttpServletRequest request) throws Exception {
		String route = (String) request.getAttribute("conf.route");

		String oransql = Constant.get(route + ".sql");
		List<String> sqlParams = Params.init(request, service).build();
		service.excuteBySql(oransql, sqlParams.toArray());

		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> item = new HashMap<String, Object>();
		item.put("id", sqlParams.get(0));
		map.put("item", item);
		map.put("code", 1);
		return map;
	}

	@RequestMapping(value = "/{tb1}/{tb2}/update")
	@ResponseBody
	public Object up(HttpServletRequest request) throws Exception {
		String route = (String) request.getAttribute("conf.route");
		String oransql = Constant.get(route + ".sql");
		List<String> sqlParams = Params.init(request, service).build();
		;
		service.excuteBySql(oransql, sqlParams.toArray());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", 1);
		return map;
	}

	@RequestMapping(value = "/{tb1}/{tb2}/del")
	@ResponseBody
	public Object del(HttpServletRequest request) throws Exception {
		String route = (String) request.getAttribute("conf.route");

		String oransql = Constant.get(route + ".sql");
		String ids = request.getParameter("ids");
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(ids)) {
			String[] split = StringUtils.split(ids, ",");
			for (String id : split) {
				service.excuteBySql(oransql, new String[] { id });
			}
			map.put("code", 1);
		}
		return map;
	}

	@RequestMapping(value = "/test/test/jsonTest")
	@ResponseBody
	public Object jsonTest(HttpServletRequest request) throws Exception {
		
		String q1 = request.getParameter("q1");
		
		
		
		JSONObject tags = new JSONObject();
		
		String[] abc={"213","23","123"};
		tags.put("tags", q1);
		String ac=tags.toJSONString();
		JSONObject jsonObject=JSONObject.parseObject(ac);
		String sql_order = "insert into article (id,title,tags) values(?,?,?)";
		List<Object> params_order = new ArrayList<Object>();
		params_order.add(0, new UUIDGenerator().generate().toString());
		params_order.add(1, "test");
		params_order.add(2, tags.toJSONString());
		service.excuteBySql(sql_order, params_order.toArray());

		String shopId = "";
		String sql_restaurant = "select id,title,tags from article";
		String res_restaurant = "id,title,tags";
		List<Map<String, Object>> article = service.queryBySqlToMap(
				sql_restaurant, new Object[] {}, res_restaurant.split(","));

		JSONObject res = new JSONObject();
		res.put("res", article);
		return res;
	}
}